package cn.lastjune.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.lastjune.pojo.Employee;
import cn.lastjune.service.EmployeeService;

@Controller
@RequestMapping("/login")
public class LoginController
{
	
	//自动依赖注入
    @Autowired
    EmployeeService employeeService;

    //登陆请求的响应处
    @RequestMapping(method = RequestMethod.GET)
    public void confirm(HttpServletRequest request, HttpServletResponse response) throws IOException
    {

        PrintWriter out = response.getWriter();
        String usr = request.getParameter("user");
        String pass = request.getParameter("pass");
        String rand=request.getParameter("randField");
        String right=(String) request.getSession().getAttribute("rand");
        boolean flag=false;
        if(right.equals(rand)){
        	flag=true;
        }
        Employee temp = employeeService.getEmployeeById(usr);
        String password = temp.getPassword();
        if (pass.equals(password))
        {
        	if(flag){
        		//System.out.print("login in!!!");
        		Cookie cookie=new Cookie("username",usr);
        		cookie.setMaxAge(60);
        		response.addCookie(cookie);
        		request.getSession().setAttribute("username", usr);
            	out.print("{success:true,msg:\'yes\'}");
            	// return "main";
            	// return "index";
            	out.flush();
            }
        	else{
        		out.print("{success:true,msg:\'error\'}");
        		out.flush();      		
        	}
        }
        else
        {
            out.print("{success:false,msg:\'no\'},{failure:true}");
            out.flush();
        }
    }
}
